package com.yuns.exam.service.impl;

//import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.yuns.course.entity.CourseType;
import com.yuns.exam.dto.ExamDto;
import com.yuns.exam.dto.QuesDto;
import com.yuns.exam.dto.QuestionDto;
import com.yuns.exam.entity.Exam;
import com.yuns.exam.entity.ExamQuestion;
import com.yuns.exam.entity.Question;
import com.yuns.exam.entity.QuestionOption;
import com.yuns.exam.mapper.ExamMapper;
import com.yuns.exam.mapper.ExamQuestionMapper;
import com.yuns.exam.mapper.QuestionMapper;
import com.yuns.exam.mapper.QuestionOptionMapper;
import com.yuns.exam.req.QuestionParam;
import com.yuns.exam.service.IQuestionService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yuns.exam.vo.QuestionVO;
import com.yuns.util.CommonExcel;
import com.yuns.util.CommonUtils;
import com.yuns.util.ListUtils;
import com.yuns.web.param.QueryParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yuns.web.param.FrontPage;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2020-10-25
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {



    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private ExamQuestionMapper examQuestionMapper;

    @Autowired
    private QuestionOptionMapper questionOptionMapper;

        @Override
        public Object selectQuestionList(FrontPage frontPage) {
            if (!frontPage.is_search()) {
                return  baseMapper.selectQuestionList(frontPage);
            }
            Page<Question> page = new Page<>(frontPage.getPageNumber(), frontPage.getPageSize());
            List<Question> list = baseMapper.selectQuestionList(page, frontPage);
            return page.setRecords(list);
     }

    @Override
    public Object selectQuestionListByCondition(QuestionParam frontPage) {
        if(!frontPage.is_search()){
            return   baseMapper.selectQuestionListByCondition(frontPage);
        }
        Page<QuestionVO> page = new Page<>(frontPage.getPageNumber(),frontPage.getPageSize());
        List<QuestionVO> list = baseMapper.selectQuestionListByCondition(page,frontPage);
        return   page.setRecords(list);
    }

    @Override
    public Object selectQuestionDetail(QuestionParam questionParam) {
        QuestionDto questionDto = QuestionDto.builder().build();
        ExamQuestion examQuestion = ExamQuestion.builder().questionId(questionParam.getData().getId()).build();
        EntityWrapper<ExamQuestion> examQuestionEntityWrapper = new EntityWrapper<>();
        examQuestionEntityWrapper.setEntity(examQuestion);
        // 同一个题目 被设置到 多个题库中
        List<ExamQuestion> examQuestion1 = examQuestionMapper.selectList(examQuestionEntityWrapper);

        if(examQuestion1 == null || examQuestion1.size() ==0){
            return null;
        }
        ExamDto t = ExamDto.builder().build();
        t.setId((examQuestion1.get(0).getExamId()));
        List<ExamDto> ts = Lists.newArrayList();
        ts.add(t);
        questionDto.setExamList(ts);
        Question t1 = Question.builder().id(Long.valueOf(examQuestion1.get(0).getQuestionId())).build();

        FrontPage<Question> frontPage = new FrontPage<>();
        frontPage.setSelectedType("id");
        frontPage.setType(String.valueOf(t1.getId()));
        List<QuesDto> t2 = questionMapper.selectQuestionDtoList(frontPage);
        Question question = Question.builder().build();
        BeanUtils.copyProperties(t2.get(0),question);

        // 查询题目内容
        questionDto.setQuestion(question);
        QuestionOption questionOption = QuestionOption.builder().questionId(examQuestion1.get(0).getQuestionId()).build();

        EntityWrapper<QuestionOption> wrapper = new EntityWrapper<>();
        wrapper.setEntity(questionOption);
        List<QuestionOption> questionOption1 = questionOptionMapper.selectList(wrapper);
        // 查询题目选项
        questionDto.setQuestionOptionList(questionOption1);
        return questionDto;
    }

    @Override
    public void exportList(QuestionParam frontPage, HttpServletResponse response) {
        try {
            List<QuestionVO> list = Lists.newArrayList();
            if(frontPage.is_search()){
                Page<QuestionVO> page = (Page<QuestionVO>)selectQuestionListByCondition(frontPage);

                list  = page.getRecords();
            }else{
                list = (List<QuestionVO>) selectQuestionListByCondition(frontPage);
            }

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            String fileName = "题目列表-" + df.format(new Date()) + ".xls";

            String[] rowsName = new String[]{"序号", "类型", "所属题库", "题目内容"};
            List<Map<String, String>> dataList = new ArrayList<>();
            Object[] objs = null;
            for (int i = 0; i < list.size(); i++) {
                Map m = new HashMap();
                objs = new Object[rowsName.length];
                objs[0] = i;
                m.put("i",i);
                objs[1] = list.get(i).getQuestionType()==0?"单选题":
                        list.get(i).getQuestionType()==1?"多选题":
                        list.get(i).getQuestionType()==2?"判断题":
                        list.get(i).getQuestionType()==3?"简答题":"" ;

                Question q = questionMapper.selectByIdSelf(list.get(i).getId());

                String questionAnswer = list.get(i).getQuestionType()==0?q.getQuestionAnswer():
                        list.get(i).getQuestionType()==1?q.getQuestionAnswer():
                                list.get(i).getQuestionType()==2?q.getQuestionAnswer():
                                        list.get(i).getQuestionType()==3?q.getQuestionAnswerReply():"" ;
                String analysis = q.getAnalysis();
                m.put("analysis",analysis);
                m.put("qanswer",questionAnswer);
                m.put("qt",objs[1] );
                objs[2] = list.get(i).getExamName();
                m.put("en",objs[2] );
                objs[3] = list.get(i).getQuestionTitle();
                m.put("qtitle",objs[3] );
                QuestionOption questionOption = QuestionOption.builder().questionId(list.get(i).getId()).build();
                EntityWrapper<QuestionOption> questionOptionEntityWrapper = new EntityWrapper<>();
                questionOptionEntityWrapper.setEntity(questionOption);
                List<QuestionOption> questionOption1 = questionOptionMapper.selectList(questionOptionEntityWrapper);
                for(QuestionOption questionOption2:questionOption1) {
                    m.put(questionOption2.getCode(), questionOption2.getContent());
                }
                dataList.add(m);
            }
            List <ExcelExportEntity> entity = new ArrayList <ExcelExportEntity>();
            entity.add(new ExcelExportEntity("题目序号", "i"));
            entity.add(new ExcelExportEntity("类型", "qt"));
            entity.add(new ExcelExportEntity("所属题库", "en"));
            entity.add(new ExcelExportEntity("题目内容", "qtitle"));
            entity.add(new ExcelExportEntity("题目答案", "qanswer"));
            entity.add(new ExcelExportEntity("题目解析", "analysis"));
            // 题目选项
            entity.add(new ExcelExportEntity("A", "A"));
            entity.add(new ExcelExportEntity("B", "B"));
            entity.add(new ExcelExportEntity("C", "C"));
            entity.add(new ExcelExportEntity("D", "D"));

            List <Map<String, String>> list1 = dataList;
            CommonUtils.exportExcel(response, entity, list1, "题目列表情况", "题目列表情况");


        } catch (Exception e) {
            throw new RuntimeException("题目列表导出失败");
        }


    }


}
